package alp.starcode.nudtportal.framework.config;

import alp.starcode.common.dict.annotations.EnableDict;
import alp.starcode.common.dict.config.DictConfigurerSupport;
import alp.starcode.common.dict.control.DictAccessControl;
import alp.starcode.common.dict.template.DictTemplate;
import alp.starcode.common.dict.template.impl.RedisDictTemplateImpl;
import alp.starcode.nudtportal.framework.util.RequestHolder;
import alp.starcode.nudtportal.framework.cache.UserCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.util.Set;

/**
 * @author: lw
 * @date: 2021/11/19 11:25
 * 数据字典使用范例：
 * 1. 启用字典：@EnableDict
 * 2. 选择dictTemplate类型： 实现dictTemplate()方法
 * 3. 字典管理后台接口的授权： 实现verifyDictUrlPermission()方法
 */
@Slf4j
@Configuration
@EnableDict
public class DictTemplateConfig extends DictConfigurerSupport implements DictAccessControl {

    @Autowired
    RedisTemplate redisTemplate;

    @Resource
    RequestHolder requestHolder;


    @Value("${spring.application.name:nudt-portal}")
    private String applicationName;

//    @Value("${dict.manage_role}")
//    private String manageRoleUuid;

    /**
     * dictTemplate实现类
     *
     * @return DictTemplate
     * @throws Exception 异常信息
     */
    @Bean
    @Override
    public DictTemplate dictTemplate() throws Exception {
        //JDBC查数据库方式
        //return new JDBCDictTemplateImpl();
        //内存缓存方式
        //return new MemoryDictTemplateImpl();
        //redis缓存
        return new RedisDictTemplateImpl(redisTemplate, applicationName);
    }

    /**
     * url访问权限回调
     *
     * @throws Exception 异常信息
     */
    @Override
    public boolean verifyDictUrlPermission() {
        //todo 配置Dict管理页面权限,返回true表示用户拥有对应权限
        Set<String> roleUuids = requestHolder.getCurrentLoginCASUser().getRoleUuids();
//        if (roleUuids.contains(manageRoleUuid)) {
            return true;
//        }
//        return false;
    }
}
